package webbandidong.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import webbandidong.viewmodel.SearchMobileViewModel;

public class SearchMobileValidator implements Validator {

    public boolean supports(Class clazz) {
        return SearchMobileViewModel.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        SearchMobileViewModel model = (SearchMobileViewModel)target;
        try {
            String fromPrice = model.getFromPrice();
            String toPrice = model.getToPrice();
            double fPrice = 0, tPrice = Double.MAX_VALUE;
            if (!"".equals(fromPrice)) {
                fPrice = Double.parseDouble(fromPrice);
            }
            if (!"".equals(toPrice)) {
                tPrice = Double.parseDouble(toPrice);
            }
            if (fPrice > tPrice) {
                errors.reject("cannot.greaterthan");
            }
            if (fPrice < 0 || tPrice < 0) {
                errors.reject("cannot.negative");
            }
        }
        catch (Exception ex) {
            errors.reject("incorect.format");
        }

        try {
            String companyId = model.getCompanyId();
            if (!"NONE".equals(companyId)) {
                Integer.parseInt(companyId);
            }
        }
        catch (Exception ex) {
            errors.reject("invalid.value");
        }
    }
}
